<template>
	<div class="flex flex-col w-full h-full mx-auto space-y-6 rounded">

		<div class="w-full h-full" ref="domChartMap"></div>

		<div class="absolute z-50 left-6">
			<el-cascader v-model="item" :options="items" @change="changeItem" placeholder="请选择" class="w-5 sm:w-60" />
		</div>

		<div class="absolute right-6 z-50 h-[90%] w-52 hidden md:block">
			<el-card class="w-full h-full" body-style="padding:0;" body-class="w-full h-full">
				<div class="w-full h-full" ref="domChartBar"></div>
			</el-card>
		</div>


	</div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted } from 'vue';
import { watchResize } from './logic';
import department from '@/common/getDepartment';
import filterData from '@/common/filterData';
import formatter from '@/common/formatter';
import svgMap from '@/assets/map.svg';
import { forEach } from 'lodash';
const { dataPool } = defineProps(['dataPool']),
	{ dataPool1, dataPool2 } = dataPool;

const department2 = department.department2.flat();

const getSvgMap = async (path) => {
	const response = await fetch(new URL(path, import.meta.url));
	const text = await response.text();
	const parser = new DOMParser();
	return parser.parseFromString(text, 'image/svg+xml');
};

const domChartMap = ref(null),
	domChartBar = ref(null);

let chartMap, chartBar;

const item = ref(['kuandai', 'kuandai_count', 'kuandai_xp', { title: '宽带新派（全部）', data: dataPool1.kuandai_xp.all, func: 'countAllList', isMinBetter: true }]),
	items = [
		{
			value: 'kuandai', label: '宽带',
			children: [
				{
					value: 'kuandai_count', label: '工单',
					children: [
						{
							value: 'kuandai_xp', label: '新派',
							children: [
								{ value: { title: '宽带新派（全部）', data: dataPool1.kuandai_xp.all, func: 'countAllList', isMinBetter: true }, label: '全部' },
								{ value: { title: '宽带新派（手机宽带）', data: dataPool1.kuandai_xp.shoukuan, func: 'countAllList', isMinBetter: true }, label: '手机宽带' },
								{ value: { title: '宽带新派（全家享）', data: dataPool1.kuandai_xp.quanjiaxiang, func: 'countAllList', isMinBetter: true }, label: '全家享' },
								{ value: { title: '宽带新派（金牛）', data: dataPool1.kuandai_xp.jinniu, func: 'countAllList', isMinBetter: true }, label: '金牛' },
								{ value: { title: '宽带新派（重点小区）', data: dataPool1.kuandai_xp.kaimenhong, func: 'countAllList', isMinBetter: true }, label: '重点小区' }
							]
						}, {
							value: 'kuandai_gd', label: '归档',
							children: [
								{ value: { title: '宽带归档（全部）', data: dataPool1.kuandai_gd.all, func: 'countAllList' }, label: '全部' },
								{ value: { title: '宽带归档（手机宽带）', data: dataPool1.kuandai_gd.shoukuan, func: 'countAllList' }, label: '手机宽带' },
								{ value: { title: '宽带归档（全家享）', data: dataPool1.kuandai_gd.quanjiaxiang, func: 'countAllList' }, label: '全家享' },
								{ value: { title: '宽带归档（金牛）', data: dataPool1.kuandai_gd.jinniu, func: 'countAllList' }, label: '金牛' },
								{ value: { title: '宽带归档（重点小区）', data: dataPool1.kuandai_gd.kaimenhong, func: 'countAllList' }, label: '重点小区' }
							]
						}, {
							value: 'kuandai_zt', label: '在途',
							children: [
								{ value: { title: '宽带在途（全部）', data: dataPool1.kuandai_zt.all, func: 'countAllList', isMinBetter: true }, label: '全部' },
								{ value: { title: '宽带在途（手机宽带）', data: dataPool1.kuandai_zt.shoukuan, func: 'countAllList', isMinBetter: true }, label: '手机宽带' },
								{ value: { title: '宽带在途（全家享）', data: dataPool1.kuandai_zt.quanjiaxiang, func: 'countAllList', isMinBetter: true }, label: '全家享' },
								{ value: { title: '宽带在途（金牛）', data: dataPool1.kuandai_zt.jinniu, func: 'countAllList', isMinBetter: true }, label: '金牛' },
								{ value: { title: '宽带在途（重点小区）', data: dataPool1.kuandai_zt.kaimenhong, func: 'countAllList', isMinBetter: true }, label: '重点小区' },
								{ value: { title: '宽带在途（超长）', data: dataPool1.kuandai_zt.chaochang, func: 'countAllList', isMinBetter: true }, label: '超长' },
								{ value: { title: '宽带在途（预警）', data: dataPool1.kuandai_zt.yujing, func: 'countAllList', isMinBetter: true }, label: '预警' }
							]
						}
					]
				}, {
					value: 'kuandai_kpi', label: '指标',
					children: [
						{ value: { title: '宽带及时率', data: dataPool2.kuandai_jishilv, func: 'kpiAllList', isPercent: true }, label: '及时率' },
						{ value: { title: '宽带回单率', data: dataPool2.kuandai_huidanlv, func: 'kpiAllList', isPercent: true }, label: '回单率' },
						{ value: { title: '宽带参评率', data: dataPool2.kuandai_canpinglv, func: 'kpiAllList', isPercent: true }, label: '参评率' },
						{ value: { title: '宽带在途归档比', data: dataPool2.kuandai_zaituguidangbi, func: 'kpiAllList', isMinBetter: true }, label: '在途归档比' },
						{ value: { title: '宽带人均产能', data: dataPool2.kuandai_renjunchanneng, func: 'kpiAllList' }, label: '人均产能' }
					]
				}
			],
		}, {
			value: 'xinyewu', label: '智家业务',
			children: [
				{
					value: 'xinyewu_count', label: '工单',
					children: [
						{
							value: 'xinyewu_xp', label: '新派',
							children: [
								{ value: { title: '智家业务新派（全部）', data: dataPool1.xinyewu_xp.all, func: 'countAllList', isMinBetter: true }, label: '全部' },
								{ value: { title: '智家业务新派（FTTR）', data: dataPool1.xinyewu_xp.FTTR, func: 'countAllList', isMinBetter: true }, label: 'FTTR' },
								{ value: { title: '智家业务新派（组网）', data: dataPool1.xinyewu_xp.zuwang, func: 'countAllList', isMinBetter: true }, label: '组网' },
								{ value: { title: '智家业务新派（看家）', data: dataPool1.xinyewu_xp.kanjia, func: 'countAllList', isMinBetter: true }, label: '看家' },
								{ value: { title: '智家业务新派（平安乡村）', data: dataPool1.xinyewu_xp.pinganxiangcun, func: 'countAllList', isMinBetter: true }, label: '平安乡村' },
								{ value: { title: '智家业务新派（门锁）', data: dataPool1.xinyewu_xp.mensuo, func: 'countAllList', isMinBetter: true }, label: '门锁' }
							]
						}, {
							value: 'xinyewu_gd', label: '归档',
							children: [
								{ value: { title: '智家业务归档（全部）', data: dataPool1.xinyewu_gd.all, func: 'countAllList' }, label: '全部' },
								{ value: { title: '智家业务归档（FTTR）', data: dataPool1.xinyewu_gd.FTTR, func: 'countAllList' }, label: 'FTTR' },
								{ value: { title: '智家业务归档（组网）', data: dataPool1.xinyewu_gd.zuwang, func: 'countAllList' }, label: '组网' },
								{ value: { title: '智家业务归档（看家）', data: dataPool1.xinyewu_gd.kanjia, func: 'countAllList' }, label: '看家' },
								{ value: { title: '智家业务归档（平安乡村）', data: dataPool1.xinyewu_gd.pinganxiangcun, func: 'countAllList' }, label: '平安乡村' },
								{ value: { title: '智家业务归档（门锁）', data: dataPool1.xinyewu_gd.mensuo, func: 'countAllList' }, label: '门锁' }
							]
						}, {
							value: 'xinyewu_zt', label: '在途',
							children: [
								{ value: { title: '智家业务在途（全部）', data: dataPool1.xinyewu_zt.all, func: 'countAllList', isMinBetter: true }, label: '全部' },
								{ value: { title: '智家业务在途（FTTR）', data: dataPool1.xinyewu_zt.FTTR, func: 'countAllList', isMinBetter: true }, label: 'FTTR' },
								{ value: { title: '智家业务在途（组网）', data: dataPool1.xinyewu_zt.zuwang, func: 'countAllList', isMinBetter: true }, label: '组网' },
								{ value: { title: '智家业务在途（看家）', data: dataPool1.xinyewu_zt.kanjia, func: 'countAllList', isMinBetter: true }, label: '看家' },
								{ value: { title: '智家业务在途（平安乡村）', data: dataPool1.xinyewu_zt.pinganxiangcun, func: 'countAllList', isMinBetter: true }, label: '平安乡村' },
								{ value: { title: '智家业务在途（门锁）', data: dataPool1.xinyewu_zt.mensuo, func: 'countAllList', isMinBetter: true }, label: '门锁' }
							]
						}
					]
				}, {
					value: 'xinyewu_kpi', label: '指标',
					children: [
						{ value: { title: '智家业务及时率', data: dataPool2.xinyewu_jishilv, func: 'kpiAllList', isPercent: true }, label: '及时率' },
						{ value: { title: '智家业务回单率', data: dataPool2.xinyewu_huidanlv, func: 'kpiAllList', isPercent: true }, label: '回单率' },
						{ value: { title: '智家业务在途归档比', data: dataPool2.xinyewu_zaituguidangbi, func: 'kpiAllList', isMinBetter: true }, label: '在途归档比' },
						{ value: { title: '智家业务人均产能', data: dataPool2.xinyewu_renjunchanneng, func: 'kpiAllList' }, label: '人均产能' },
						{ value: { title: '智家业务质检通过率', data: dataPool2.xinyewu_zhijiantongguolv, func: 'kpiAllList', isPercent: true }, label: '质检通过率' }
					]
				}
			],
		}, {
			value: 'tousu', label: '投诉',
			children: [
				{
					value: 'tousu_count', label: '工单',
					children: [
						{
							value: 'tousu_xp', label: '新派',
							children: [
								{ value: { title: '投诉新派（全部）', data: dataPool1.tousu_xp.all, func: 'countAllList', isMinBetter: true }, label: '全部' },
								{ value: { title: '投诉新派（电视）', data: dataPool1.tousu_xp.dianshi, func: 'countAllList', isMinBetter: true }, label: '电视' },
							]
						},
						{
							value: 'tousu_gd', label: '归档',
							children: [
								{ value: { title: '投诉归档（全部）', data: dataPool1.tousu_gd.all, func: 'countAllList' }, label: '全部' },
								{ value: { title: '投诉归档（电视）', data: dataPool1.tousu_gd.dianshi, func: 'countAllList' }, label: '电视' },
							]
						},
						{
							value: 'tousu_zt', label: '在途',
							children: [
								{ value: { title: '投诉在途（全部）', data: dataPool1.tousu_zt.all, func: 'countAllList', isMinBetter: true }, label: '全部' },
								{ value: { title: '投诉在途（电视）', data: dataPool1.tousu_zt.dianshi, func: 'countAllList', isMinBetter: true }, label: '电视' },
								{ value: { title: '投诉在途（VIP）', data: dataPool1.tousu_zt.vip, func: 'countAllList', isMinBetter: true }, label: 'VIP' },
								{ value: { title: '投诉在途（超长）', data: dataPool1.tousu_zt.chaochang, func: 'countAllList', isMinBetter: true }, label: '超长' },
								{ value: { title: '投诉在途（预警）', data: dataPool1.tousu_zt.yujing, func: 'countAllList', isMinBetter: true }, label: '预警' }
							]
						}
					]
				}, {
					value: 'tousu_kpi', label: '指标',
					children: [
						{ value: { title: '投诉及时率', data: dataPool2.tousu_jishilv, func: 'kpiAllList', isPercent: true }, label: '及时率' },
						{ value: { title: '投诉驳回率', data: dataPool2.tousu_bohuilv, func: 'kpiAllList', isPercent: true, isMinBetter: true }, label: '驳回率' },
						{ value: { title: '投诉在途归档比', data: dataPool2.tousu_zaituguidangbi, func: 'kpiAllList', isMinBetter: true }, label: '在途归档比' },
						{ value: { title: '投诉人均产能', data: dataPool2.tousu_renjunchanneng, func: 'kpiAllList' }, label: '人均产能' },
						{ value: { title: '投诉参评率', data: dataPool2.tousu_canpinglv, func: 'kpiAllList', isPercent: true }, label: '参评率' },
						{ value: { title: '重复投诉率', data: dataPool2.chongfutousulv, func: 'kpiAllList', isPercent: true, isMinBetter: true }, label: '重复投诉率' }
					]
				}
			],
		},{
      value: 'zhiliang', label: '网络质量',
      children: [
        { value: { title: '弱光表现值', data: dataPool2.ruoguangbiaoxianzhi, func: 'kpiAllList', isPercent: true ,isMinBetter: true }, label: '弱光表现值' },
        { value: { title: '新增整治量', data: dataPool2.xinzengzhengzhiliang, func: 'kpiAllList', }, label: '新增整治量' }
      ]
    }
	]

const changeItem = (e = item.value) => {
	e = e[e.length - 1];
	const { isPercent = false, isMinBetter = false } = e;
	const source = filterData[e.func](e.data);

	let chartData = {
		timelineDate: source.date,
		options: source.data.map((row, index) => ({
			series: [
				{
					data: row.filter(item => department2.includes(item.name))
				}
			]
		}))
	};

	chartData.options.forEach((item, index) => {

		const values = item.series[0].data.map(item => item.value),
			min = Math.min(...values),
			max = Math.max(...values);

		chartData.options[index].visualMap = {
			min,
			max,
			range: [min, max],
		};
		chartData.options[index].title = {
			text: e.title,
			subtext: formatter.excelDate(chartData.timelineDate[index])
		};
	});

	console.log('分布数据', chartData)
	setMapChart(chartData, { isPercent, isMinBetter })

}

const displayEffect = (isMinBetter) => {
	return isMinBetter ? {
		text: ['劣', '优'],
		color: ['#94D315', '#FFB942', '#FF4B38']
	} : {
		text: ['优', '劣'],
		color: ['#FF4B38', '#FFB942', '#94D315']
	}
}
const rangeColor = (total, current, colors) => {
	const interval = total / colors.length;
	const index = Math.min(Math.floor(current / interval), colors.length - 1);
	return colors[index];
};

const setMapChart = (chartData, baseInfo) => {
	const { isPercent, isMinBetter } = baseInfo;
	const effect = displayEffect(isMinBetter);

	const optionMap = {
		title: {
			left: 'center',
		},
		tooltip: {
			formatter: (params) =>
				`${params.marker}${params.name} ${formatter.valueToText(params.value, isPercent)}`,
		},
		visualMap: {
			left: '10%',
			bottom: '10%',
			orient: 'vertical',
			text: effect.text,
			realtime: true,
			calculable: true,
			formatter: (value) => formatter.valueToText(value, isPercent),
			controller: { inRange: { color: effect.color } },
			inRange: { color: effect.color },
			target: { color: effect.color },
		},
		timeline: {
			axisType: 'category',
			autoPlay: false,
			playInterval: 2000,
			symbol: 'none',
			checkpointStyle: {
				borderWidth: 2
			},
			controlStyle: {
				showNextBtn: false,
				showPrevBtn: false
			},
			data: chartData.timelineDate,
			currentIndex: chartData.timelineDate.length - 1,
			label: {
				rotate: 20,
				formatter: (params) => formatter.excelDate(params, 'M/D')
			},
			left: '8%',
			right: '8%',
			bottom: 0,
		},
		series: [
			{
				type: 'map',
				map: 'mm',
				roam: true,
				emphasis: {
					label: {
						show: false,
					},
				},
				selectedMode: false
			},
		],
		options: chartData.options,
		baseInfo
	};
	chartMap.setOption(optionMap, false);
	setBarChart();
}

const setBarChart = () => {
	const option = chartMap.getOption(),
		{ data } = option.series[0],
		{ baseInfo } = option;
	const { isPercent, isMinBetter } = baseInfo;
	const effect = displayEffect(isMinBetter);
	data.sort((a, b) => a.value - b.value);

	const optionBar = {
		tooltip: {
			formatter: (params) => `${params.marker}${params.name} ${formatter.valueToText(params.value, isPercent)}`
		},
		grid: {
			top: '2%',
			bottom: '0%',
			containLabel: true
		},

		xAxis: { show: false },
		yAxis: {
			data: data.map(e => e.name)
		},
		series: [
			{
				type: 'bar',
				data: data.map((e, index) => ({
					value: e.value,
					label: {
						show: true,
						formatter: (params) => formatter.valueToText(params.value, isPercent),
						align: 'left',
						offset: [5, 0]
					},
					itemStyle: {
						color: rangeColor(data.length, index + 1, effect.color)
					}
				}))
			}
		]
	}
	chartBar.setOption(optionBar, false);
}

const charts = window.allCharts['FenBu'];

onMounted(async () => {

	charts['fenBuMap'] = chartMap = echarts.init(domChartMap.value, null, {
		renderer: 'canvas',
		useDirtyRect: false,
	});

	charts['fenBuBar'] = chartBar = echarts.init(domChartBar.value);

	const svg = await getSvgMap(svgMap);
	echarts.registerMap('mm', { svg });

	chartMap.on('timelinechanged', function (params) {
		setBarChart();
	});

	changeItem();

	watchResize({ chartMap });
	watchResize({ chartBar });

});

</script>

<style scoped></style>
